# coding=utf-8
# author=haishan09@gmail.com
import json
from common.configs import BaseConfig, configmanager

EMPTY_CHOICE = [('', '------'), ]

class CutShipConfig(BaseConfig):

    templ = [
    ]

    def __init__(self, name=None, label=None, config=None, initial=None, dim=None):
        super(CutShipConfig, self).__init__(name, label, config, initial)
        if dim:
            self.config += [
            {'name': 'initial', 'label': u'初始值', 'widget': 'TextInput', 'type': 'string', 'default': ''},
            {'name': 'visiable', 'label': u'是否显示', 'widget': 'Checkbox', 'type': 'string', 'default': True},
            {'name': 'editable', 'label': u'是否可编辑', 'widget': 'Checkbox', 'type': 'string', 'default': True},
        ]

        if dim and dim.dtype == 1:
            self.config.append({
                'name': 'range',
                'label': u'可范围选择',
                'widget': 'Checkbox',
                'default': 1,
            })

class CubeShipDimensionConfig(BaseConfig):

    templ = [
        {'name': 'drilldown', 'label': u'维度', 'widget': 'TextInput', 'type': 'string', 'default': ''},
        {'name': 'initial', 'label': u'过滤', 'widget': 'TextInput', 'type': 'string', 'default': ''},
        {'name': 'selected', 'label': u'是否下钻', 'widget': 'Checkbox', 'type': 'string', 'default': False},
        {'name': 'rank', 'label': u'序列号', 'widget': 'NumberInput', 'type': 'int', 'default': 0},
    ]

    def __init__(self, name=None, label=None, config=None, initial=None, dim=None):
        super(CubeShipDimensionConfig, self).__init__(name, label, config, initial)
        if dim:
            self.config[0]['default'] = dim.name


class CubeShipAggregateConfig(BaseConfig):

    templ = [
        {'name': 'aggregate', 'label': u'指标', 'widget': 'TextInput', 'type': 'string', 'default': ''},
        {'name': 'expression', 'label': u'表达式', 'widget': 'TextInput', 'type': 'string', 'default': ''},
        {'name': 'selected', 'label': u'是否展示', 'widget': 'Checkbox', 'type': 'string', 'default': False},
        {'name': 'rank', 'label': u'序列号', 'widget': 'NumberInput', 'type': 'int', 'default': 0},
    ]

    def __init__(self, name=None, label=None, config=None, initial=None, agg=None):
        super(CubeShipAggregateConfig, self).__init__(name, label, config, initial)
        if agg:
            self.config[0]['default'] = agg.name


class CubeShipOrderByConfig(BaseConfig):

    templ = [
        {'name': 'target', 'label': u'排序对象', 'widget': 'Select', 'type': 'string', 'default': '', 'choices': EMPTY_CHOICE},
        {'name': 'order_by', 'label': u'排序方式', 'widget': 'Select', 'type': 'string', 'default': '', 'choices': EMPTY_CHOICE + [('asc', u'顺序'), ('desc', u'逆序')]},
        {'name': 'rank', 'label': u'序列号', 'widget': 'NumberInput', 'type': 'int', 'default': 0},
    ]

    def __init__(self, name=None, label=None, config=None, initial=None, choices=[]):
        super(CubeShipOrderByConfig, self).__init__(name, label, config, initial)
        self.name = self.initial and self.initial.get('target') or None
        if choices:
            self.config[0]['choices'] += choices 


class CubeShipBasicConfig(BaseConfig):

    templ = [
        {'name': 'hide_when_cut', 'label': u'选中时隐藏', 'widget': 'Select', 'type': 'string', 'default': '', 'choices': EMPTY_CHOICE},
        {'name': 'show_when_cut', 'label': u'选中时显示', 'widget': 'Select', 'type': 'string', 'default': '', 'choices': EMPTY_CHOICE},

    ]

    def __init__(self, name=None, label=None, config=None, initial=None, choices=[]):
        super(CubeShipBasicConfig, self).__init__(name, label, config, initial)
        if choices:
            self.config[1]['choices'] += choices 
            self.config[1]['choices'] += choices 


class CubeShipConfig(BaseConfig):

    templ = [
        {'name': 'drilldowns', 'pk': 'drilldown', 'label': u'维度', 'widget': 'JsonifyListConfigWidget', 'type': 'string', 'default': '', 'configs': []},
        {'name': 'aggregates', 'pk': 'aggregate', 'label': u'指标', 'widget': 'JsonifyListConfigWidget', 'type': 'string', 'default': '', 'configs': []},
        {'name': 'orders', 'pk': 'target', 'label': u'排序', 'widget': 'JsonifyListConfigWidget', 'type': 'string', 'default': '', 'configs': []},
        {'name': 'chart', 'label': u'图表', 'widget': 'JsonifyConfigWidget', 'type': 'string', 'default': '', 'config': BaseConfig()}, 
        {'name': 'base', 'label': u'显示', 'widget': 'JsonifyConfigWidget', 'type': 'string', 'default': '', 'config': BaseConfig()}, 
    ]

    def __init__(self, name=None, label=None, config=None, cube=None, chart=None, initial=None):
        super(CubeShipConfig, self).__init__(name, label, config, initial)
        self._initial(cube, chart)

    def _initial(self, cube, chart):
        if cube:
            dim_choices = []
            agg_choices = []
            drilldowns_initial = sorted(map(lambda x: json.loads(x), json.loads(self.initial.get('drilldowns'))), key=lambda x: x['rank'])
            aggregates_initial = sorted(map(lambda x: json.loads(x), json.loads(self.initial.get('aggregates'))), key=lambda x: x['rank'])
            orders_initial = sorted(map(lambda x: json.loads(x), json.loads(self.initial.get('orders'))), key=lambda x: x['rank'])
            for data in drilldowns_initial:
                d = cube.dimensions.filter(name=data['drilldown']).first()
                if d:
                    drilldownconfig = CubeShipDimensionConfig(name=d.name, label=d.label, dim=d)
                    self.config[0]['configs'].append(drilldownconfig)
                    dim_choices.append((d.name, d.label))
            for d in cube.dimensions.exclude(name__in=map(lambda x: x[0], dim_choices)):
                drilldownconfig = CubeShipDimensionConfig(name=d.name, label=d.label, dim=d)
                self.config[0]['configs'].append(drilldownconfig)
            for data in aggregates_initial:
                a = cube.aggregates.filter(name=data['aggregate']).first()
                if a:
                    aggregateconfig = CubeShipAggregateConfig(name=a.name, label=a.label, agg=a)
                    self.config[1]['configs'].append(aggregateconfig)
                    agg_choices.append((a.name, a.label))
            for a in cube.aggregates.exclude(name__in=map(lambda x: x[0], agg_choices)):
                aggregateconfig = CubeShipAggregateConfig(name=a.name, label=a.label, agg=a)
                self.config[1]['configs'].append(aggregateconfig)
            for i in range(2):
                initial = len(orders_initial) >= (i+1) and orders_initial[i] or None
                orderconfig = CubeShipOrderByConfig(name='orderby_%s' % i, label=u'排序', initial=initial, choices=dim_choices + agg_choices)
                self.config[2]['configs'].append(orderconfig)
            self.config[4]['config'] = CubeShipBasicConfig(choices=dim_choices)
        if chart:
            self.config[3]['config'] = configmanager.get_config('chart', chart.name)()


